<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      title="库位设置"
      align="center"
      :visible.sync="dialogStorageSpace"
      @closed="closeDialog"
    >
      <div>
        <el-table :data="storageAreaData" border style="height: auto">
          <el-table-column label="所属仓库" align="center">
            <template slot-scope="scope">
              {{ scope.row.storageName }}
            </template>
          </el-table-column>
          <el-table-column label="所属库区">
            <template slot-scope="scope">
              {{ scope.row.areaName }}
            </template>
          </el-table-column>
          <el-table-column label="库位总数">
            <template slot-scope="scope">
              {{ scope.row.storageSpaceCount }}
            </template>
          </el-table-column>
          <el-table-column label="已用库位数">
            <template slot-scope="scope">
              {{ scope.row.occupiedCount }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div
        class="base-content-operate"
        align="left"
        style="padding-top: 10px; padding-bottom: 10px"
      >
        <el-button icon="el-icon-plus" type="primary" @click="onNew"
          >库位生成器</el-button
        >
        <el-button icon="el-icon-printer" type="primary" @click="toPrintBarcode"
          >打印库位标签</el-button
        >
        <!-- <el-button icon="el-icon-printer" type="primary" @click="setPrint">打印库位标签</el-button> -->
      </div>
      <div v-loading.lock="loading" class="base-content">
        <div class="basic-info">
          <el-table
            :data="list"
            element-loading-text="Loading"
            fit
            highlight-current-row
          >
            <!-- <el-table :data="list" height="calc(100% - 130px)" :header-cell-style="{ height: '50px' }"
            :cell-style="{ height: '50px' }" style="width: 100%;overflow: auto;"> -->
            <el-table-column align="center" label="序号" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="库位编号">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.number"
                  autocomplete="off"
                  maxlength="50"
                  onkeyup="this.value = this.value.replace(/[^\w_-]/g, '');"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="库位标签" width="270">
              <template slot-scope="scope">
                <JsBarcode :value="scope.row.number" :valid="true"></JsBarcode>
              </template>
            </el-table-column>
            <el-table-column label="库位状态">
              <template slot-scope="scope">
                <el-select v-model="scope.row.status">
                  <el-option label="启用" :value="1" />
                  <el-option label="禁用" :value="2" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="是否仅单一危化品">
              <template slot-scope="scope">
                <el-select v-model="scope.row.isSingleCategory">
                  <el-option label="是" :value="1" />
                  <el-option label="否" :value="2" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="是否仅单一批次">
              <template slot-scope="scope">
                <el-select v-model="scope.row.isSameBatch">
                  <el-option label="是" :value="1" />
                  <el-option label="否" :value="2" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="使用限制">
              <template slot-scope="scope">
                <el-select v-model="scope.row.usageLimit">
                  <el-option
                    v-for="item in usageLimitOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="是否占用">
              <template slot-scope="scope">
                {{ scope.row.usageStatus == 1 ? "空闲" : "占用" }}
              </template>
            </el-table-column>
          </el-table>
          <BasePagination
            :total="pagination.total"
            :current-page="pagination.pageIndex"
            :page-count="pagination.total"
            @changePage="changePage"
            @sizeChange="sizeChange"
          />
        </div>
      </div>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="closeDialog">返 回</el-button>
        <el-button type="primary" @click="onSubmit()">保 存</el-button>
      </div>
      <!-- 库位生成器 -->
      <el-dialog
        width="25%"
        :append-to-body="true"
        title="库位生成器"
        align="center"
        :visible.sync="dialogStorageSpaceGenerate"
        @closed="closeInnerDialog"
      >
        <el-form
          ref="formData"
          style="display: block"
          :label-width="formLabelWidth"
          :model="formData"
          :rules="formDataRules"
          status-icon
        >
          <el-form-item
            label="库位层数"
            :label-width="formLabelWidth"
            prop="storageSpaceX"
            :error="errorMsg.storageSpaceX"
          >
            <el-input-number
              v-model="formData.storageSpaceX"
              :min="1"
              :max="100"
              :step="1"
              step-strictly
            ></el-input-number>
          </el-form-item>
          <el-form-item
            label="库位列数"
            :label-width="formLabelWidth"
            prop="storageSpaceY"
            :error="errorMsg.storageSpaceY"
          >
            <el-input-number
              v-model="formData.storageSpaceY"
              :min="1"
              :max="100"
              :step="1"
              step-strictly
            ></el-input-number>
          </el-form-item>
          <el-form-item
            label="是否仅单一危化品"
            :label-width="formLabelWidth"
            prop="isSingleCategory"
          >
            <el-select v-model="formData.isSingleCategory">
              <el-option label="是" :value="1" />
              <el-option label="否" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="是否仅单一批次"
            :label-width="formLabelWidth"
            prop="isSameBatch"
          >
            <el-select v-model="formData.isSameBatch">
              <el-option label="是" :value="1" />
              <el-option label="否" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="使用限制"
            :label-width="formLabelWidth"
            prop="usageLimit"
          >
            <el-select v-model="formData.usageLimit">
              <el-option label="无" :value="0" />
              <el-option label="全部" :value="1" />
              <el-option label="出库" :value="2" />
              <el-option label="入库" :value="3" />
              <el-option label="除调拨、移位和盘点外的全部" :value="4" />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" align="center">
          <el-button @click="closeInnerDialog">关 闭</el-button>
          <el-button
            type="primary"
            :disabled="isDisabled"
            @click="onGenerate('formData')"
            >生成库位</el-button
          >
        </div>
      </el-dialog>
    </el-dialog>
    <div
      id="printDiv"
      ref="printDiv"
      style="display: none; width: 60mm; height: 40mm"
    >
      <div
        v-for="item in list"
        :key="item.number"
        style="page-break-after: always; vertical-align: middle; height: 70px"
      >
        <img
          :src="item.number | creatBarCode(item.number)"
          style="max-width: 100%; max-height: 100%"
        />
      </div>
    </div>
    <iframe
      ref="printIframe"
      frameborder="0"
      scrolling="no"
      style="margin: 0px; padding: 0px; width: 0px; height: 0px"
    ></iframe>
  </div>
</template>

<script>
import {
  batchCreate,
  batchUpdate,
  getList,
  getStorageAreaById,
} from "../../../api/Storage/StorageSpace.js";
import JsBarcode from "../../../components/JsBarcode.vue";
import BarcodeJs from "jsbarcode";
export default {
  name: "StorageSpaceEdit",
  components: { JsBarcode },
  filters: {
    creatBarCode(barCodeData) {
      console.log("触发条码生成事件");
      const canvas = document.createElement("canvas");
      BarcodeJs(canvas, barCodeData, {
        format: "CODE128",
        displayValue: true,
        height: 40,
        width: 2,
        textAlign: "center",
        font: "cursive",
        fontOptions: "bold",
        fontSize: 20,
        textMargin: 5,
      });
      return canvas.toDataURL("image/png");
    },
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      dialogStorageSpace: false,
      dialogStorageSpaceGenerate: false,
      dialogPrintSet: false,
      isDisabled: false,
      formLabelWidth: "150px",
      storageName: "",
      areaName: "",
      storageAreaData: [],
      list: [],
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      usageLimitOptions: [
        { value: 0, label: "无" },
        { value: 1, label: "全部" },
        { value: 2, label: "出库" },
        { value: 3, label: "入库" },
        { value: 4, label: "除调拨、移位和盘点外的全部" },
      ],
      initData: {
        storageId: 0,
        storageAreaId: 0,
        storageSpaceX: 1,
        storageSpaceY: 1,
        status: 1,
        isSingleCategory: 2,
        isSameBatch: 2,
        usageLimit: 0,
      },
      formData: {
        storageId: 0,
        storageAreaId: 0,
        storageSpaceX: 1,
        storageSpaceY: 1,
        status: 1,
        isSingleCategory: 2,
        isSameBatch: 2,
        usageLimit: 0,
      },
      formDataRules: {
        storageSpaceX: [
          {
            required: true,
            trigger: "blur",
            message: "请输入需要生成的库位列数",
          },
        ],
        storageSpaceY: [
          {
            required: true,
            trigger: "blur",
            message: "请输入需要生成的库位层数",
          },
        ],
      },
      initErrorMsg: {
        storageSpaceX: "",
        storageSpaceY: "",
      },
      errorMsg: {
        storageSpaceX: "",
        storageSpaceY: "",
      },
    };
  },
  watch: {
    value: function() {
      this.dialogStorageSpace = this.value;
      if (this.value) {
        this.init();
      }
    },
  },
  methods: {
    async init() {
      this.formData.storageAreaId = this.editId;
      getStorageAreaById({ id: this.editId })
        .then((res) => {
          const obj = res.data ? res.data : {};
          this.formData.storageId = obj.storageId;
          this.storageAreaData = [];
          this.storageAreaData.push(obj);
          this.storageName = obj.storageName;
          this.areaName = obj.areaName;
        })
        .catch(() => {});
      this.getList();
    },
    getList() {
      this.loading = true;
      getList({ storageAreaId: this.editId }, this.pagination)
        .then((res) => {
          this.list = res.data.dataList ? res.data.dataList : [];
          this.pagination.total = res.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    onGenerate() {
      this.$refs.formData.validate((valid) => {
        if (
          valid &&
          this.formData.storageId > 0 &&
          this.formData.storageAreaId > 0
        ) {
          this.isDisabled = true;
          batchCreate(this.formData)
            .then((res) => {
              if (res.code === 200) {
                this.closeInnerDialog();
              } else {
                this.showValidateMsgCheck(res);
              }
              this.loading = false;
              this.isDisabled = false;
            })
            .catch((err) => {
              console.log("batchCreate 异常");
              console.log(err);
              this.loading = false;
              this.isDisabled = false;
            });
        } else {
          return false;
        }
      });
    },
    onSubmit() {
      let numberRepeat = "";
      const numberArrs = this.list.map((item) => item.number);
      const isRepeat = numberArrs.some((item, index, arr) => {
        numberRepeat = item;
        return arr.indexOf(item) !== index;
      });
      if (isRepeat) {
        this.$message.error("库位编号:" + numberRepeat + "重复存在");
        return false;
      }
      this.loading = true;
      const requestData = {
        StorageSpaceList: this.list,
      };
      batchUpdate(requestData)
        .then((res) => {
          if (res.code === 200) {
            this.closeDialog();
          } else {
            this.showValidateMsgCheck(res);
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    changePage(val) {
      this.pagination.pageIndex = val;
      this.getList();
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getList();
    },
    closeDialog() {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = 10;
      this.pagination.total = 0;

      this.$emit("input", false);
      this.$parent.getList();
    },
    closeInnerDialog() {
      this.init();
      this.$refs.formData.resetFields();
      this.dialogStorageSpaceGenerate = false;
    },
    onNew() {
      this.dialogStorageSpaceGenerate = true;
    },
    // 关闭窗体回调函数
    DialogCall() {
      this.init();
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("storageSpaceX", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("storageSpaceY", this.errorMsg, res.msg);
      }
    },
    changeValue(value) {
      this.formData.storageSpaceX = "";
    },
    validateNumber(rule, value, callback) {
      if (!value || value < 1 || value > 100) {
        callback(new Error("请输入1~100的正整数"));
      } else {
        callback();
      }
    },
    // 标签打印
    toPrintBarcode() {
      var printIframe = this.$refs.printIframe;
      var html = this.$refs.printDiv.innerHTML;
      printIframe.setAttribute("srcdoc", html);
      printIframe.onload = function() {
        console.log(printIframe.contentWindow);
        // 去掉iframe里面的dom的body的padding margin的默认数值
        printIframe.contentWindow.document.body.style.padding = "0px";
        printIframe.contentWindow.document.body.style.margin = "0px";
        // 开始打印
        printIframe.contentWindow.focus();
        printIframe.contentWindow.print();
      };
    },
    deactivated() {
      var printIframe = this.$refs.printIframe;
      var html = this.$refs.printDiv.innerHTML;
      printIframe.setAttribute("srcdoc", html);
      printIframe.onload = function() {
        printIframe.contentWindow.focus();
        printIframe.contentWindow.close();
      };
      console.log("deactivated");
    },
  },
};
</script>
